package com.rpframework.utils

import org.apache.commons.lang.StringUtils
import java.net.InetAddress
import javax.servlet.http.HttpServletRequest

/*--扩展-*/

/**
 * @return 获取请求基本路径 requestURI-contextPath
 */
fun HttpServletRequest.getReqUriBase(): String {
    var requestURI = this.requestURI
    val contextPath = this.contextPath

    if (!StringUtils.isBlank(contextPath))
        requestURI = requestURI.removePrefix(contextPath)

    return requestURI
}

/**
 * @return 获取请求基本路径 requestURI-contextPath 并且将URL标准化
 *          比如 /list/ 转传成 /list
 */
fun HttpServletRequest.getReqUriBaseParseStandard(): String {
    var reqUriBase = this.getReqUriBase();

    val last = reqUriBase.lastOrNull()
    if (last == '/') reqUriBase = reqUriBase.substring(0, reqUriBase.length - 1)

    return reqUriBase
}

/**
 * 客户端请求IPv4地址
 */
fun HttpServletRequest.requestIpAddress(): String {
    val unknown = "UNKNOWN"
    var ipAddress = this.getHeader("x-forwarded-for")
    if (ipAddress == null || ipAddress.isEmpty() || unknown == (ipAddress).toUpperCase()) {
        ipAddress = this.getHeader("Proxy-Client-IP");
    }
    if (ipAddress == null || ipAddress.isEmpty() || unknown == (ipAddress).toUpperCase()) {
        ipAddress = this.getHeader("WL-Proxy-Client-IP");
    }
    if (ipAddress == null || ipAddress.isEmpty() || unknown == (ipAddress).toUpperCase()) {
        ipAddress = this.remoteAddr;
        if (ipAddress == "127.0.0.1") {
            //根据网卡取本机配置的IP
            val inet = InetAddress.getLocalHost()
            ipAddress = inet.hostAddress
        }
    }

    //对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
    if (ipAddress != null && ipAddress.length > 15) {
        if (ipAddress.indexOf(",") > 0) {
            ipAddress = ipAddress.substring(0, ipAddress.indexOf(","))
        }
    }
    return ipAddress
}


/**
 * HttpRequest WEB 工具类
 * Created by 刘兴 on 2016/11/2.
 */
object HttpServletUtils {
}